package com.example.mongodblab;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.example.mongodblab.model.ContentLabel;
import com.example.mongodblab.model.sub.ContentWord;
import com.example.mongodblab.service.UpdateAfieldByBfield;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.Arrays;
import java.util.List;

@SpringBootApplication
public class MongodbLabApplication {
    private static MongoTemplate mongoTemplate;

    private static UpdateAfieldByBfield updateAfieldByBfield;


    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(MongodbLabApplication.class, args);

        mongoTemplate = context.getBean(MongoTemplate.class);
        updateAfieldByBfield = context.getBean(UpdateAfieldByBfield.class);

        updateAfieldByBfield.test();
    }




    private static void save() {
        ContentLabel contentLabel = new ContentLabel();
        //contentLabel.setManualWord(List.of(new ContentWord("a", "b", "c")));
        mongoTemplate.save(contentLabel);
    }

    private static void remove() {
        mongoTemplate.dropCollection(ContentLabel.class);
    }

    private static void update() {
        String contentIdStr = "6603ef74ec74d57c2b92a291,6603efa5ba806b45c6958066";
        List<String> contentId = List.of(contentIdStr.split(","));

        List<ContentWord> add = List.of(new ContentWord("a1", "b1", "c1"), new ContentWord("a2", "b2", "c2"));

        List<ContentWord> delete = List.of(new ContentWord("a", "b", "c"));

        Query query = Query.query(Criteria.where("_id").in(contentId));

        Update update = new Update();

//        update.set("manualWord", new ArrayList<ContentWord>());

        update.addToSet("manualWord").each(ArrayUtil.toArray(add, ContentWord.class));

//        update.pullAll("manualWord", ArrayUtil.toArray(add, ContentWord.class));

        mongoTemplate.updateMulti(query, update, ContentLabel.class);
    }

    private static void find() {
        List<ContentLabel> all = mongoTemplate.findAll(ContentLabel.class);
        System.out.println(JSONUtil.toJsonStr(all));
    }
}
